package com.jmz.apt.api.service.auth;

import com.jmz.apt.api.Utils.ValidatorBizUtil;
import com.jmz.apt.api.dao.AdminDao;
import com.jmz.apt.api.entity.dbEntity.JmzAdminUser;
import com.jmz.apt.api.enums.ResponseCode;
import com.jmz.apt.api.exception.BusinessException;
import com.jmz.apt.api.message.request.Condition;
import com.jmz.apt.api.message.request.Query;
import com.jmz.apt.api.message.request.RequestMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLSyntaxErrorException;
import java.util.List;

/**
 * Created by fanglexue on 2019/11/2.
 */

@Component
public class Login {

    @Autowired AdminDao adminDao;

    @Autowired
    ValidatorBizUtil validatorBizUtil;

    public JmzAdminUser LoginFindAdminUser(RequestMessage requestMessage) {
        List<Condition> conditions = requestMessage.getMessage().getBody().getQuery().getCondition();
        Query query = requestMessage.getMessage().getBody().getQuery();
        if (conditions.isEmpty() || conditions == null) {
            throw new BusinessException(ResponseCode.ILLEGAL_ARGUMENTS.getCode(),
                    ResponseCode.LOSE_ARGUMENTS.getDesc());
        }
        String errorMsg = validatorBizUtil.checkCondition(conditions, "login");
        if (StringUtils.isNotEmpty(errorMsg)) {
            // 参数校验失败，抛出异常。
            throw new BusinessException(ResponseCode.ILLEGAL_ARGUMENTS.getCode(), errorMsg);
        }

        List<JmzAdminUser> jmzAdminUsers = adminDao.findAdmin("*", conditions, query);
        if (!jmzAdminUsers.isEmpty() && jmzAdminUsers != null) {
            return jmzAdminUsers.get(0);
        }

        return  null;

    }
}
